import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'
import { myAjaxJson, getAuthShop, isLogining, ROOTURL} from './../publicAPI/publicAPI'

class WorkloadM extends Component {

  constructor (props, context) {
      super(props, context);
      console.log("初始化");

      this.state = {
        //page: 1,
        delete: false,
        deleteId: '',
        assistantData: [],
        workloadM: [],
        isChoosedM: {true: '是', false: '否'},
        attachingId: '',

        
        
      };

      let _this = this;
      //获取所有店铺信息
      getAuthShop(null, function(data) {
        console.log(data);
        var shopsForAdm = [];
        let shopsM = {};
        data.forEach((shopMes) => {
          shopsForAdm.push(shopMes.dname);
          shopsM[shopMes.id] = shopMes.dname
        }); 
        console.log(shopsForAdm);
        this.setState({
          //shopsData: data,
          shopsForAdm: shopsForAdm,
          shopsM: shopsM,
        });
      }.bind(_this));

      //获取所有服务人员信息
      myAjaxJson(ROOTURL +'servant/profile/search.api', 'POST', {}, function(data) {
        console.log(data);
        let servantsM = {};
        data.forEach(function(servant) {
          servantsM[servant.id] = servant.meta.name;
        });
        console.log(servantsM);
        this.setState({
            servantsM: servantsM,
        });
      }.bind(_this), function(error) {})

  }

  

  componentWillMount() {
    console.log("将安装");
    let _this = this;
    this.handleGetInfo();
  }

  componentDidMount() {
      console.log("安装成功");

  }

  handleGetInfo() {
    let _this = this;
    myAjaxJson(ROOTURL +'contract/offline/search.api', 'POST', {}, function(data) {
      console.log(data);
      let workloadM = data.filter(function(workloadData) {
          return !workloadData.dd&&!workloadData.attaching
      });
      console.log(workloadM);
      this.setState({
          workloadM: workloadM,
      });
    }.bind(_this), function(error) {})
  }

  /*handleClick() {

  }*/

  handleDelete(id) {
    let _this = this;
    myAjaxJson(ROOTURL +'contract/offline/search.api', 'POST', {attaching: id}, function(data) {
      data.map(function(workloadData, idx) {
        if(workloadData.attaching) {
          _this.setState({
            attachingId: workloadData.id,
          });
        }
      });
    }, function(error) {});
    this.setState({
      delete: !this.state.delete,
      deleteId: id
    })
  }

  deleteWorkloadM(){
      var _this = this;

      _this.setState({
        delete: !_this.state.delete
      });

      let token = isLogining();
      fetch(ROOTURL + 'contract/offline/instance.api?id=' + this.state.deleteId, {
        method: 'DELETE',
        headers: {
          "X-Cafune-Authentication": "SECRET",
          "X-Cafune-Session-Token": token,
          "Content-type": "application/json; charset=UTF-8"
        },
        body: JSON.stringify({})
      })
      .then((res) => {
        if (res.ok) {
            //删除从点单
            if(_this.state.attachingId) {
              fetch(ROOTURL + 'contract/offline/instance.api?id=' + _this.state.attachingId, {
                method: 'DELETE',
                headers: {
                  "X-Cafune-Authentication": "SECRET",
                  "X-Cafune-Session-Token": token,
                  "Content-type": "application/json; charset=UTF-8"
                },
                body: JSON.stringify({})
              })
              .then((res) => {
                if(res.ok) {
                  _this.handleGetInfo();
                }
              })
              .catch((err) => {
                alert('删除失败,从订单删除失败');
              });
            }
          } else {
            alert('删除失败，主订单删除失败');
            console.log("Looks like the response wasn't perfect, got status", res.status);
          }

      })
      .catch(function (error) {
          alert('删除失败');
          console.log('Request failed', error);
      });
  }

  tHead() {
    var data = [
      {name: "订单号"},
      {name: "审核"},
      {name: "服务项目"},
      {name: "理发师"},
      {name: "所属门店"},
      {name: "是否指定"},
      {name: "理发师助理"},
      {name: "标准价格"},
      {name: "实收"},
      {name: "收款方式"},
      {name: "服务开始时间"},
      {name: "操作"}
    ];
    const _headArr = [];
    const _width = {
      "0" : "5%",//id
      "1" : "3%",//订单审核
      "2" : "15%",//服务项目
      "3" : "10%",//理发师
      "4" : "20",//所属门店
      "5" : "5%",//是否指定
      "6" : "8%",//理发师助理
      "7" : "5%",//标准价格
      "8" : "5%",//实收
      "9" : "5%",//收款方式
      "10" : "10%",//服务时间
      "11" : "15%",//操作
    };
    //_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
    _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
    return _headArr;
  }

  tBody() {
 
        return this.state.workloadM.map((item) => {
          let tmServe = new Date(item.tmServe);
          return (
            <tr key={item.id}>
              <td>{item.id}</td>  
              <td>
                {
                  item.meta.isChecked? (<img style={{width: '20px', position: 'relative', top: '6px'}} src={require(`./../imgs/workloadM_${item.meta.permission}.png`)} />) : (<img style={{width: '20px', position: 'relative', top: '6px'}} src={require('./../imgs/workloadM_wait.png')} />)
                }
              </td>   
              <td>{item.meta.serType}</td>
              <td>{this.state.servantsM[item.servantId]}</td>
              <td>{this.state.shopsM[item.shopId]}</td>
              <td>{this.state.isChoosedM[item.meta.isChoosed]}</td> 
              <td>{item.meta.assistant}</td> 
              <td>{item.grossPay}</td> 
              <td>{item.netPay}</td>
              <td>{item.meta.payment}</td> 
              <td>{tmServe.getFullYear()}-{tmServe.getMonth()+1}-{tmServe.getDate()} {tmServe.getHours()}:{tmServe.getMinutes()}</td>
              <td>
                <span><NavLink  to={`/SalaryM/WorkloadM/${item.id}`} className="rbtn green">详细</NavLink></span>
                <span style={{marginLeft: '12px'}}><NavLink  to={`/SalaryM/WorkloadMCheck/${item.id}`} className="rbtn green">审核</NavLink></span>
                <span className="rbtn red" onClick={this.handleDelete.bind(this, item.id)} style={{marginLeft: "15px"}}>删除</span>
              </td>
            </tr>
          )
        })

    
  }


  
    render() {
      return (
        <div>
        <div className="rt-wrap">
                  <h2 className="catagory">
                    <span className="cata-title">线下订单管理</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <span><img style={{width: '20px', position: 'relative', top: '5px'}} src={require('./../imgs/workloadM_true.png')} />--审核通过</span>&nbsp;&nbsp;&nbsp;&nbsp;
                    <span><img style={{width: '20px', position: 'relative', top: '5px'}} src={require('./../imgs/workloadM_false.png')} />--审核未通过</span>&nbsp;&nbsp;&nbsp;&nbsp;
                    <span><img style={{width: '20px', position: 'relative', top: '5px'}} src={require('./../imgs/workloadM_wait.png')} />--等待审核</span>
                    <Link to={`/SalaryM/WorkloadInput`}>
                      <button className="add-btn" />
                    </Link>
                  </h2>
        
                  <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()} />
                </div>
                {
                  this.state.delete ?
                    <div id={style.msgDialog}>
                      <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
                        <div className={style['msgDialog_button']}>
                          <button id={style['msgDialog_yes']} onClick={this.deleteWorkloadM.bind(this)}>确定</button>
                          <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
                        </div>
                      </div>
                    </div> : null
                }
        </div>
      )
    }
}

export default WorkloadM
